﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public interface IPurge
{
    void PrePurge();

    void Purge();
}

/// <summary>
/// 重新加载时，释放掉所有单例
/// 
/// 使用方法：将需要释放的单例 用Regist注册进来
/// </summary>
public class PurgeMgr
{
    List<IPurge> _list;

    List<IPurge> list
    {
        get
        {
            if(null == _list)
                _list = new List<IPurge>();

            return _list;
        }
    }

    static PurgeMgr _instance;

    static PurgeMgr instance
    {
        get
        {
            if(null == _instance)
            {
                _instance = new PurgeMgr();
            }

            return _instance;
        }
    }

    // MonoBenhaviour不允许注册
    public static void Regist(IPurge purge)
    {
        Debugger.Assert(!(purge is MonoBehaviour), "purge must not be MonoBehaviour");
        instance.list.Add(purge);
    }

    public static void Remove(IPurge purge)
    {
        if (checkListEmpty())
            return;

        instance.list.Remove(purge);
    }

    public static void PrePurge()
    {
        if (checkListEmpty())
            return;

        for (int i = 0; i < _instance._list.Count; i++)
            _instance._list[i].PrePurge();
    }

    public static void Purge()
    {
        if (checkListEmpty())
        {
            _instance = null;
            return;
        }

        var ins = _instance;
        _instance = null;
        int count = ins._list.Count;
        for (int i = 0; i < count; i++)
        {
            ins._list[i].Purge();
        }

        ins._list.Clear();
        ins._list = null;
    }

    static bool checkListEmpty()
    {
        return _instance == null || _instance._list== null || _instance._list.Count == 0;
    }
}
